import { Form, Input } from 'antd'
import globalConfig from '@/core/framework/config/globalConfig'
import React, { useEffect, useState } from 'react'
import controllerUtils from '@/core/utils/controllerUtils'
import captchaImageService from '@/core/captcha/service/captchaImageService'
import { SafetyOutlined } from '@ant-design/icons'

const CaptchaImageFormItem = (props: any) => {
	const codePlaceholder = globalConfig.mock ? '验证码：8888' : '验证码：'
	const codeValue = globalConfig.mock ? '8888' : ''
	const [codeState, setCodeState] = useState(codeValue)
	const [imgSrcState, setImgSrcState] = useState('')
	const form = Form.useFormInstance()
	const captchaItemIdFieldName = 'captchaItemId'
	// 刷新
	const onRefresh = async () => {
		await controllerUtils
			.of(async () => {
				const codeRes = await captchaImageService.createBase64ByLogin()
				form.setFieldValue(captchaItemIdFieldName, codeRes.captchaItemId)
				setImgSrcState(codeRes.base64Data)
				console.log(codeRes)
			})
			.catchLog()
	}
	useEffect(() => {
		onRefresh()
	}, [])
	return (
		<>
			<Form.Item name={captchaItemIdFieldName} hidden={true}>
				<Input />
			</Form.Item>
			<Form.Item>
				<Form.Item
					name="code"
					initialValue={codeState}
					rules={[{ required: true }]}
					style={{ display: 'inline-block', width: 'calc(50% - 8px)' }}
				>
					<Input prefix={<SafetyOutlined />} placeholder={codePlaceholder} />
				</Form.Item>
				<Form.Item style={{ display: 'inline-block', width: 'calc(50% - 8px)', margin: '0 8px' }}>
					<img src={imgSrcState} onClick={onRefresh} />
				</Form.Item>
			</Form.Item>
		</>
	)
}
export default CaptchaImageFormItem
